package cn.youyeku.zsxh.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import cn.youyeku.zsxh.R;
import cn.youyeku.zsxh.Utils.AppConfig;
import cn.youyeku.zsxh.Utils.LogUtils;
import cn.youyeku.zsxh.api.AsyncHttpHelp;
import cn.youyeku.zsxh.api.XhApi;
import cn.youyeku.zsxh.common.Contanst;
import cn.youyeku.zsxh.db.YeDBConnect;

import cn.youyeku.zsxh.ui.home.PrivateMessage;
import okhttp3.Request;


public class MessageService extends Service implements MessageType {


    //获取消息线程
    private MessageThread messageThread = null;


    //通知栏消息
    private int messageNotificationID = 1000;
    private String senderId;


    private NotificationManager mNotificationManager;
    private NotificationCompat.Builder mBuilder;


    private YeDBConnect db;

    private String pre_create = "CREATE TABLE IF NOT EXISTS \"%s\" (\n" +
            "\"id\"  INTEGER,\n" +
            "\"sender_id\"  INTEGER,\n" +
            "\"message_content\"  TEXT,\n" +
            "\"nick_name_me\"  TEXT,\n" +
            "\"send_time\"  TEXT,\n" +
            "\"nick_name\"  TEXT,\n" +
            "\"message_status\"  INTEGER DEFAULT 0,\n" +
            "\"message_type\"  INTEGER \n" +
            ");\n";


    Request getMessageRequest = new Request.Builder()
            .url(XhApi.BASE_URL + XhApi.API_GET_PRIVATE_MESSAGE)
            .build();

    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(this);

        db = YeDBConnect.getInstance(getApplicationContext(), 'w'); //获取数据库连接
        db.execute(String.format(pre_create,AppConfig.CONF_USER_ID));

        //开启线程
        messageThread = new MessageThread();
        messageThread.start();


        return super.onStartCommand(intent, flags, startId);
    }


    /**
     * 从服务器端获取消息
     */
    class MessageThread extends Thread {
        //运行状态，下一步骤有大用


        public void run() {
            Log.w("s", "开始线程");
            LogUtils.w(pre_create);


            while (true) {
                try {
                    Thread.sleep(5000);
                    LogUtils.w("server is running");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (AppConfig.CONF_RECEIVE_MESSAGE) {
                    try {

                        //同步信息
                        String response = AsyncHttpHelp.mOkHttpClient.newCall(getMessageRequest).execute().body().string();

                        JSONArray data;
                        JSONObject object = new JSONObject(response);
                        LogUtils.w(response);
                        data = object.getJSONArray("data");

                        if (data.length() > 0) {
                            LogUtils.w("不能运行到这里");

//                        JSONArray array = new JSONArray();
                            String sql_values = "";
                            int arr_len = data.length();
                            for (int i = 0; i < arr_len; i++) {
                                JSONObject temp = (JSONObject) data.get(i);
                                String sender_id = temp.getString("sender_id");
                                String Message = temp.getString("message_content");
                                String SenderTime = temp.getString("send_time");
                                String nickName = temp.getString("nick_name");
                                showMessage("收到消息", Message, sender_id,nickName);


                                if(Contanst.ON_CHAT &&PrivateMessage.uid.equals(sender_id)){
                                    //把数据发送到聊天窗口
                                    //发送广播
                                    Intent intent=new Intent();
                                    intent.putExtra("content", Message);
                                    intent.putExtra("time", SenderTime);
                                    intent.setAction("cn.youyeku.zsxh.service");
                                    sendBroadcast(intent);

                                }

                                if (arr_len - 1 == i) {
                                    sql_values += String.format("('%s',%s,'%s','%s',%s,%s)", nickName,sender_id, Message, SenderTime, MESSAGE_NOT_READ, MESSAGE_TYPE_FRIEND);

                                } else {
                                    sql_values += String.format("('%s',%s,'%s','%s',%s,%s),", nickName,sender_id, Message, SenderTime, MESSAGE_NOT_READ, MESSAGE_TYPE_FRIEND);
                                }

                            }

//                            LogUtils.w(sql_values);
                            db.execute(String.format("INSERT INTO `%s` (nick_name,sender_id,message_content,send_time,message_status,message_type) " +
                                    "VALUES %s",AppConfig.CONF_USER_ID, sql_values));

                        }


                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

        }


        private void showMessage(String title, String Text, String sender_id,String nick) {
            mBuilder.setContentTitle(title)//设置通知栏标题
                    .setContentText(Text)
                    .setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL, getApplicationContext(), PrivateMessage.class, sender_id,nick))
//                    .setTicker("测试通知来啦") //通知首次出现在通知栏，带上升动画效果的
                    .setWhen(System.currentTimeMillis())//通知产生的时间，会在通知信息里显示，一般是系统获取到的时间
                    .setOngoing(false)
                    .setDefaults(Notification.DEFAULT_SOUND)
                    .setSmallIcon(R.drawable.ic_back);//设置通知小ICON
            mNotificationManager.notify(messageNotificationID, mBuilder.build());

        }
    }

    public PendingIntent getDefalutIntent(int flags, Context context, Class B, String uid,String title) {

        Intent intent = new Intent(context, B);
        intent.putExtra("uid", uid);
        intent.putExtra("title", title);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        return PendingIntent.getActivity(context, 0, intent, flags);

    }


}